import React from 'react'
import { notification, Layout, Modal, Form, Input, Button, Row, Col, Icon, message } from 'antd'
const { Header, Footer, Sider, Content } = Layout;
import { withRouter, Link } from 'react-router-dom';
const urlTools = require('url');
import md5 from 'md5';
import api from '../../api/mailFindPassword';

const FormItem = Form.Item

import './index.less'

class MailForm extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      disabledMailSend: false,
      sendWord: '发送验证码'
    }
  }

  sendSubmit(e) {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (err) {
        return;
      }
      // 每次提交改变验证码
      // this.setState({
      //   captcha : this.changeUrl(this.state.captcha)
      // });
      const formData = this.props.form.getFieldsValue();
      this.setState({
        disabledMailSend: true
      })
      api.post("/sendMail", formData).then((res) => {
        let data = res.data;
        if (data.code == 0) {
          this.props.form.resetFields(["mailCode"]);
          this.props.form.setFields({
            mailCode: {
              value: formData.mailCode
            }
          });
          let i = 60;
          let timer = setInterval(() => {
            this.setState({
              sendWord: i--
            });
            if (i == 0) {
              clearInterval(timer);
              this.setState({
                sendWord: '发送验证码',
                disabledMailSend: false
              });
            }
          }, 1000);
          Modal.success({
            title: '发送邮件成功',
            content: '请登录你绑定的邮箱"' + data.data.email + '"查看验证码'
          });
        } else {
          message.error(data.message);
          if (data.messages) {
            data.messages.forEach(item => {
              var obj = {};
              obj[item.field] = {
                value: formData[item.field],
                errors: [new Error(item.error)]
              }
              this.props.form.setFields(obj);
            });
          }
          this.setState({
            disabledMailSend: false
          })
        }
      }).catch((e) => {
        this.setState({
          disabledMailSend: false
        })
        message.error("操作失败,请稍后在试");
        console.error(e);
        console.error(e.response);
      });
    });
  }

  okSubmit() {
    this.props.form.validateFields((err, values) => {
      const formData = this.props.form.getFieldsValue()
      if (!formData.mailCode || formData.mailCode.trim().length == 0) {
        this.props.form.setFields({
          mailCode: {
            value: formData.mailCode,
            errors: [new Error('邮箱验证码不能为空')],
          },
        });
        return;
      }
      if (!formData.mailCode && formData.mailCode.trim().length != 4) {
        this.props.form.setFields({
          mailCode: {
            value: formData.mailCode,
            errors: [new Error('邮箱验证码为4个字符')],
          },
        });
        return;
      }
      if (err) {
        return;
      }

      api.post("/validMailCode", formData).then((res) => {
        let data = res.data;
        if (data.code == 0) {
          this.props.okMailModal(formData);
        } else {
          message.error(data.message);
          if (data.messages) {
            data.messages.forEach(item => {
              var obj = {};
              obj[item.field] = {
                value: formData[item.field],
                errors: [new Error(item.error)]
              }
              this.props.form.setFields(obj);
            });
          }
        }
      }).catch((e) => {
        console.error(e);
        console.error(e.response);
        message.error("操作失败,请稍后在试");
      });


    });
  }

  mailCodeChange(event) {
    let config = {
      mailCode: {
        value: event.target.value
      }
    }
    if (event.target.value.trim().length != 4) {
      config.mailCode.errors = [new Error("邮箱验证码为4位字符")];
    }
    this.props.form.setFields(config);
  }

  cancelMailModal = () => {
    this.props.cancelMailModal();
  }

  toLogin() {
    this.props.history.replace('/login');
  }

  changeUrl = (url) => {
    let obj = urlTools.parse(url, true);
    let urlPrefix = url.substring(0, url.indexOf("?"));
    return urlPrefix + "?captchaToken=" + obj.query.captchaToken + "&random" + Math.ceil(Math.random() * 9000 + 1000);
  }

  changeImage = (event) => {
    this.setState({
      captcha: this.changeUrl(this.state.captcha)
    })
  }

  config = {
    clearForm: () => {
      this.props.form.resetFields();
    },
    loadCaptcha: (callback) => {
      api.get("/getCaptcha").then((res) => {
        let data = res.data;
        if (data.code == 0) {
          this.setState({
            captcha: data.data.imageCaptchaUrl + "&random=" + Math.ceil(Math.random() * 9000 + 1000)
          });
          this.props.form.setFieldsValue({
            imageCaptchaToken: data.data.imageCaptchaToken
          })
          callback && callback(true);
        }
      }).catch((e) => {
        console.error(e);
        console.error(e.response);
        message.error("载入失败,请稍后在试");
        callback && callback(false);
      });
    }
  }

  componentDidMount = () => {
    this.props.componentDidMount(this.config);
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form layout="horizontal" onSubmit={this.sendSubmit.bind(this)} className="mail-form">
        <Row>
          <Col span="24">
            {getFieldDecorator('imageCaptchaToken', {
            })(
              <Input type="hidden" />
              )}
            <FormItem>
              {getFieldDecorator('loginId', {
                rules: [{ required: true, message: '账号不能为空!' },
                { min: 6, message: '账号不能低于6个字符' }],
              })(
                <Input prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder='请输入账号' />
                )}
            </FormItem>
          </Col>
          <Col span="16">
            <FormItem>
              {getFieldDecorator('imageCode', {
                rules: [{ required: true, message: '图片验证码不能为空!' },
                { min: 4, message: '图片验证码为4个字符' },
                { max: 4, message: '图片验证码为4个字符' }],
              })(
                <Input prefix={<Icon type="code-o" style={{ fontSize: 13 }} />} placeholder='请输入4位验证码,点击图片切换' />
                )}
            </FormItem>
          </Col>
          <Col span="7" offset="1">
            <img className="image-code" src={this.state.captcha} onClick={this.changeImage.bind(this)} />
          </Col>
          <Col span="16">
            <FormItem>
              {getFieldDecorator('mailCode', {
              })(
                <Input onChange={this.mailCodeChange.bind(this)} prefix={<Icon type="code-o" style={{ fontSize: 13 }} />} placeholder='请输入4位邮箱验证码' />
                )}
            </FormItem>
          </Col>
          <Col span="7" offset="1">
            <Button className="btn-register" size="large" loading={this.state.loading} loading={this.state.loading} disabled={this.state.disabledMailSend} htmlType='submit'>{this.state.sendWord}</Button>
          </Col>
        </Row>
        <Row>
          <Col span="24">
            <Button className="btn-login" type="primary" size="large" icon="check-circle" onClick={this.okSubmit.bind(this)}>确认</Button>
          </Col>
        </Row>
        <Row>
          <Col span="24">
            <Button className="btn-login" type="button" size="large" icon="poweroff" onClick={this.cancelMailModal.bind(this)}>关闭</Button>
          </Col>
        </Row>
      </Form>
    )
  }
}


class ManageForm extends React.Component {
  state = {
    loading: false
  };
  submit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({
          loading: true
        });
        values.password = md5(values.password);
        api.put('/modifyPassword', values).then((res) => {
          const result = res.data;
          if (result.code == 0) {
            message.success('修改成功！');
            this.props.okPasswordModal();
          } else {
            message.error(result.message);
            if (result.messages) {
              result.messages.forEach((item => {
                if (item.field == 'mailCode') {
                  message.error(item.error);
                }
              }));
            }
          }
          this.setState({
            loading: false
          });
        }).catch(e => {
          console.error(e);
          message.error("提交失败");
          this.setState({
            loading: false
          });
        });
      }
    });
  }

  clear = () => {
    this.props.form.resetFields();
  }

  checkPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次新密码输入不一样!');
    } else {
      callback();
    }
  }
  checkConfirm = (rule, value, callback) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  }

  handleConfirmBlur = (e) => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  }

  componentDidMount = () => {
    this.props.componentDidMount({ clear: this.clear });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 14,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };

    return (
      <Form className="passowrd-form" layout="horizontal" onSubmit={this.submit}>
        {getFieldDecorator('loginId', {
          initialValue: this.props.record.loginId
        })(
          <Input type="hidden" />
          )}
        {getFieldDecorator('mailCode', {
          initialValue: this.props.record.mailCode
        })(
          <Input type="hidden" />
          )}
        <FormItem
          {...formItemLayout}
          label="密码"
          hasFeedback
        >
          {getFieldDecorator('password', {
            rules: [{ required: true, message: '密码不能为空!' },
            { min: 6, message: '密码不能低于6个字符' },
            {
              validator: this.checkConfirm,
            }],
            initialValue: ''
          })(
            <Input type="password" />
            )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="确认密码"
          hasFeedback
        >
          {getFieldDecorator('confirm', {
            rules: [{ required: true, message: '确认密码不能为空!' }, {
              validator: this.checkPassword,
            }],
            initialValue: ''
          })(
            <Input type="password" onBlur={this.handleConfirmBlur} />
            )}
        </FormItem>
        <FormItem {...tailFormItemLayout}>
          <Button loading={this.state.loading} type="primary" htmlType="submit" size="large" style={{ marginRight: '10px' }}>提交</Button>
          <Button onClick={this.clear} disabled={this.state.loading}>清空</Button>
        </FormItem>
      </Form>
    );
  }
}

const PasswordForm = Form.create()(ManageForm);

const Mail = Form.create()(MailForm);

class FindType extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      mailModal: false,
      mailVisibility: "visible",
      passwordModal: false,
      passwordRecord: { loginId: "", mailCode: "" }
    }
  }

  handleSubmit(e) {
    e.preventDefault();
    this.setState({
      loading: true
    });
    const data = this.props.form.getFieldsValue()
    if (data.user === undefined || data.password === undefined || data.confirmpassword === undefined) {
      this.setState({
        loading: false
      });
      message.error("Incorrect user or password or confirmpassword");
    } else if (data.password !== data.confirmpassword) {
      this.setState({
        loading: false
      });
      message.error("please input correct password and confirmpassword");
    } else {
      this.setState({
        loading: false
      });
      this.toLogin();
      message.success("Welcome " + data.user + " please login.")
    }
  }

  mobile = () => { }
  mail = () => {
    this.setState({
      mailModal: true,
      mailVisibility: "hidden"
    });
    this.mailConfig.loadCaptcha((success) => {
      if (!success) {
        this.setState({
          mailModal: false,
          mailVisibility: "hidden"
        });
        return;
      }
      this.setState({
        mailModal: true,
        mailVisibility: "visible"
      });
    });
  }
  cancelMailModal = () => {
    this.setState({
      mailModal: false
    });
    this.mailConfig.clearForm();
  }
  okMailModal = (record) => {
    this.state.passwordRecord = record;
    this.setState({
      mailModal: false,
      passwordModal: true
    });
  }
  toLogin() {
    this.props.history.replace('/login');
  }
  mailComponentDidMount = (config) => {
    this.mailConfig = config;
    this.setState({
      mailModal: false,
      mailVisibility: "hidden"
    });
  }

  passwordComponentDidMount = (config) => {
    this.passwordConfig = config;
  }

  componentDidMount = () => {
    this.setState({
      mailModal: true,
      mailVisibility: "hidden"
    });
  }

  okPasswordModal = () => {
    this.props.history.replace('/login');
  }

  cancelPasswordModal = () => {
    this.setState({
      passwordModal: false
    })
    this.passwordConfig.clear();
  }

  render() {
    return (
      <div className="wrap">
        <Modal
          title="邮箱找回密码"
          visible={this.state.mailModal}
          maskStyle={{ "visibility": this.state.mailVisibility }}
          bodyStyle={{ "visibility": this.state.mailVisibility }}
          style={{ "visibility": this.state.mailVisibility }}
          onOk={this.okMailModal}
          maskClosable={false}
          onCancel={this.cancelMailModal}
          wrapClassName="vertical-center-modal"
          width="500"
          footer={null}
        >
          <Mail okMailModal={this.okMailModal} cancelMailModal={this.cancelMailModal} componentDidMount={this.mailComponentDidMount} />
        </Modal>
        <Modal
          title="修改密码"
          visible={this.state.passwordModal}
          onOk={this.okPasswordModal}
          maskClosable={false}
          onCancel={this.cancelPasswordModal}
          wrapClassName="vertical-center-modal"
          width="500"
          footer={null}
        >
          <PasswordForm okPasswordModal={this.okPasswordModal} record={this.state.passwordRecord} cancelPasswordModal={this.cancelPasswordModal} componentDidMount={this.passwordComponentDidMount} />
        </Modal>
        <Row className="find" type="flex" justify="center" align="middle">
          <Col span="8">
            <Button className="find-by-mail" size="large" icon="mail" loading={this.state.loading} onClick={this.mail.bind(this)}>邮箱找回</Button>
            <Button className="find-by-mobile" size="large" icon="mobile" htmlType='button' onClick={this.mobile.bind(this)}>手机找回</Button>
            <Link to="/login"><Button className="find-by-mobile" size="large" icon="mobile" htmlType='button' /*onClick={this.toLogin.bind(this)}*/>返回登录</Button></Link>
          </Col>
        </Row>
      </div>
    )
  }
}

export default withRouter(FindType)
